'use client';

import { useState, useEffect } from 'react';
import { Box, Container, Typography, Card, CardContent, Button, Alert, Snackbar, CircularProgress } from '@mui/material';
import { useRouter } from 'next/navigation';
import { examApi } from '@/api/exams';
import dayjs from 'dayjs';

interface ExamResult {
  id: number;
  title: string;
  subject: string;
  score: number;
  passingScore: number;
  totalScore: number;
  completedAt: string;
  passed: boolean;
}

export default function ProfilePage() {
  const [examResults, setExamResults] = useState<ExamResult[]>([]);
  const [loading, setLoading] = useState(true);
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' });
  const router = useRouter();

  useEffect(() => {
    const user = localStorage.getItem('user');
    if (!user) {
      router.push('/login');
      return;
    }

    fetchExamResults();
  }, [router]);

  const fetchExamResults = async () => {
    try {
      setLoading(true);
      const data = await examApi.getStudentExamResults();
      setExamResults(data);
    } catch (error) {
      setSnackbar({
        open: true,
        message: '获取考试成绩失败',
        severity: 'error'
      });
    } finally {
      setLoading(false);
    }
  };

  const handleViewDetail = (examId: number) => {
    router.push(`/student-exams/${examId}/result`);
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-screen">
        <CircularProgress size={60} />
      </div>
    );
  }

  return (
    <Container maxWidth="lg" sx={{ mt: 4 }}>
      <Typography variant="h4" component="h1" gutterBottom>
        我的成绩
      </Typography>

      {examResults.length === 0 ? (
        <Typography variant="body1" color="textSecondary">
          暂无考试记录
        </Typography>
      ) : (
        <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 3 }}>
          {examResults.map((result) => (
            <Card key={result.id} sx={{ height: '100%' }}>
              <CardContent>
                <Typography variant="h6" gutterBottom>
                  {result.title}
                </Typography>
                <Typography color="textSecondary" gutterBottom>
                  科目：{result.subject}
                </Typography>
                <Box sx={{ mt: 2 }}>
                  <Typography variant="body2" color={result.passed ? 'success.main' : 'error.main'}>
                    得分：{result.score} / {result.totalScore}
                  </Typography>
                  <Typography variant="body2">
                    及格分：{result.passingScore}
                  </Typography>
                  <Typography variant="body2">
                    考试时间：{dayjs(result.completedAt).format('YYYY-MM-DD HH:mm')}
                  </Typography>
                  <Typography variant="body2" color={result.passed ? 'success.main' : 'error.main'}>
                    状态：{result.passed ? '及格' : '不及格'}
                  </Typography>
                </Box>
                <Box sx={{ mt: 2, display: 'flex', justifyContent: 'flex-end' }}>
                  <Button
                    variant="outlined"
                    size="small"
                    onClick={() => handleViewDetail(result.id)}
                  >
                    查看详情
                  </Button>
                </Box>
              </CardContent>
            </Card>
          ))}
        </Box>
      )}

      <Snackbar
        open={snackbar.open}
        autoHideDuration={3000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
      >
        <Alert severity={snackbar.severity as any} sx={{ width: '100%' }}>
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Container>
  );
}